// pages/goods_list/goods_list.js
import {request} from '../../request/index.js'

Page({

    /**
     * 页面的初始数据
     */
    data: {
        tabs:[
            {id:1,value:'综合',isActive:true},
            {id:2,value:'销量',isActive:false},
            {id:3,value:'价格',isActive:false}
        ],
        goodsList:[]
    },
    queryParams:{
        query:'',
        cid:'',
        pagenum:1,    //当前的页码值
        pagesize:10  //每页显示多少条数据
    },
    totalPages:'',
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        console.log(options.cid)
        this.queryParams.cid = options.cid
        this.getGoodsList();
    },
    async getGoodsList(){
        const {data:res} = await request({url:"https://api-hmugo-web.itheima.net/api/public/v1/goods/search",data:this.queryParams});
        console.log(res)
        let total = res.message.total;
        this.totalPages = Math.ceil(total / this.queryParams.pagesize);
        this.setData({
            //这里是为了防止加载下一页数据的时候 ， 下一页数据覆盖上一页数据 , 所以这里采取的是 用 解构 拼接下一页数组
            goodsList:[...this.data.goodsList, ...res.message.goods]
        });
        wx.stopPullDownRefresh()
    },
    handletabsItemChange(e){
        let {index} = e.detail;
        let {tabs} = this.data;
        tabs.forEach((v,i)=>{index===i?v.isActive=true:v.isActive=false;});
        this.setData({
            tabs
        })
    },
    onReachBottom:function(){
        if(this.queryParams.pagenum>=this.totalPages){
            wx.showToast({
                title: '没有更多数据了',
            });
        }else{
            this.queryParams.pagenum++;
            this.getGoodsList();
        }
    },
    onPullDownRefresh:function(){
        this.setData({
            goodsList:[]
        });
        this.queryParams.pagenum = 1;
        this.getGoodsList();
    }
    
})